package com.ss.project.xia17user.config.sys;

import com.ss.project.xia17user.common.redis.RedisUtils;
import com.ss.project.xia17user.config.security.form.LoginMethod;
import com.ss.project.xia17user.dao.entity.Config;
import com.ss.project.xia17user.service.ConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 系统配置管理
 * @author xia17
 * @date 2020/9/18 13:50
 */
@Component
@RequiredArgsConstructor
public class SysConfigManager {

    private static final String CONFIG_REDIS_KEY_PREFIX = "SYS_CONFIG_";

    private final RedisUtils redisUtils;
    private final ConfigService configService;

    /**
     * 是否支持这个登录方式
     * 如果支持那么会返回登录方式
     * @param loginMethod /
     * @return /
     */
    public LoginMethod supportLoginMethod(String loginMethod){
        LoginMethod method;
        try {
            method =  LoginMethod.valueOf(loginMethod);
        }catch (RuntimeException e){
            return null;
        }
        switch (method){
            case PASSWORD:{
                return getConfig(ConfigKey.PASSWORD_LOGIN).forBoolean() ? method : null;
            }
            case EMAIL_CODE:{
                return getConfig(ConfigKey.EMAIL_LOGIN).forBoolean() ? method : null;
            }
        }
        return null;
    }

    /**
     * 获取配置
     * @param key /
     * @return /
     */
    public ConfigValue getConfig(ConfigKey key){
        String redisKey = this.generateRedisKey(key);
        Object value = redisUtils.get(redisKey);
        if (value != null){
            return new ConfigValue((String) value);
        }
        Config config = configService.getConfig(key);
        // 30分钟有效
        redisUtils.set(redisKey,config.getValue(),30 , TimeUnit.MINUTES);
        return new ConfigValue(config.getValue());
    }

    /**
     * 生成redisKey
     * @param key /
     * @return /
     */
    private String generateRedisKey(ConfigKey key){
        return CONFIG_REDIS_KEY_PREFIX + key.name() + ":";
    }


}
